`
https://leetcode.cn/problems/maximum-white-tiles-covered-by-a-carpet/
`

/**
 * @param {number[][]} tiles
 * @param {number} carpetLen
 * @return {number}
 */
var maximumWhiteTiles = function (tiles, carpetLen) {
  const n = tiles.length
  // 按最左边的瓷砖排序
  tiles.sort((a, b) => a[0] - b[0])
  let res = 0
  let cover = 0
  let left = 0, right = 0

  // 枚举每段瓷砖的右端点来摆放毯子的右端点
  while (right < n) {
    const [tl, tr] = tiles[right++]
    cover += tr - tl + 1

    // 左指针 left 需要满足其指向的那段瓷砖的右端点被毯子覆盖
    const carpetLeft = tr - carpetLen + 1
    while (tiles[left][1] < carpetLeft) {
      // tiles[left] 完全不在窗口中
      // 减掉 left 那段瓷砖，收缩窗口
      cover -= tiles[left][1] - tiles[left][0] + 1
      left++
    }

    // tiles[left] 中的小于 carpetLeft 的这部分不在窗口中
    // 计算，如果是负数就不需要减
    const uncover = Math.max(carpetLeft - tiles[left][0], 0)
    res = Math.max(res, cover - uncover)
  }

  return res
};